<?php


namespace app\api\controller\v25;


use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlFortuneUp;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\FortuneCache;
use app\common\model\FortuneNote;
use app\common\model\Recode;
use think\Log;

class Fortune extends Auth
{
    protected $active_switch;

    public function _initialize()
    {
        parent::_initialize();
        $this->active_switch = false;
    }

    /**
     * @title 每日运势详情
     * @method GET
     * @desc
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */

    public function dayFortuneHistory()
    {
        $rid = input('get.rid/d', 0);
        $dayNoteId = input('get.day_note_id/d', 0);
        $orderId = input('get.order_id/s', '');
        $day = input('get.day/s', '');
        $uid = (int)$this->user['id'];
        if (!$dayNoteId)
        {
            if (!$rid)
            {
                return show(config('code.error'), '档案信息获取失败');
            }

            $recode = (new Recode())->getRecode(['id' => $rid]);
            if (!$recode || $recode['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '档案不存在');
            }
            $day = date('Y-n-j', strtotime($day));
            //获取日运详情数据
            $data = (new FortuneCache())->getHistoryDayFortuneInfo($uid, 2, $day, $rid, $orderId);

            $unlockRecodeInfo = (new Util)->getFortuneDetailRecodeInfo([$recode]);
            $data['unlock_recode_info'] = ['info' => $unlockRecodeInfo];
        } else
        {
            $data = (new FortuneCache())->getHistoryDayFortuneInfo($uid, 1, $day, $rid, $dayNoteId);
        }

        return show(200, '加载成功', $data);
    }

    /**
     * 运势信息新增厄运消除数据结构
     * @param array $data
     * @param int $rid
     * @param int $isSelf
     * @param int $time
     * @return array
     * @throws \Exception
     */
    private function fortuneDataReset(array $data, int $rid, int $isSelf, int $time): array
    {
        // $colors = [
        //     0 => ['name' => '困难', 'color' => '#7775ff',],
        //     1 => ['name' => '警戒', 'color' => '#ffa536',],
        //     2 => ['name' => '平平', 'color' => '#ffed17',],
        //     3 => ['name' => '吉利', 'color' => '#00f4e7',],
        //     4 => ['name' => '大吉', 'color' => '#00e9a0',],
        // ];
        foreach ($data['fortune_list'] as $index => $fortuneItem)
        {
            $data['fortune_list'][$index]['is_bad_luck'] = in_array($fortuneItem['color'], ['#ffed17', '#ffa536', '#7775ff'], true) ? 1 : 0;
            $data['fortune_list'][$index]['fortune_up_tip'] = $this->fortuneUpText[$fortuneItem['name']]['fortune_up_tip'];
            $data['fortune_list'][$index]['pid'] = $this->fortuneUpText[$fortuneItem['name']]['pid'];
            $data['fortune_list'][$index]['lucky_tip'] = $this->fortuneUpText[$fortuneItem['name']]['lucky_tip'];
        }

        if ($isSelf && (($timeDate = date('Ymd', $time)) === date('Ymd')))
        {
            $timeDate = (int)$timeDate;
            // 获取运势提升状态 1已提升 0未提升
            $isFortuneUp = (new ZlFortuneUp())->getFortuneUpStatus($rid, $timeDate);
            $data['fortune_up_btn_show'] = 0; //默认不提示

            $textList = [];
            foreach ($data['fortune_list'] as $fortuneItem)
            {
                if (!$fortuneItem['is_bad_luck'])
                {
                    $textList[] = [
                        'text' => $this->fortuneUpText[$fortuneItem['name']]['lucky_text'],
                        'color' => '#FFFFFF'
                    ];
                    continue;
                }

                if ($isFortuneUp)
                {   // 已提升运势
                    $textList[] = [
                        'text' => $this->fortuneUpText[$fortuneItem['name']]['lucky_text'],
                        'color' => '#00f4e7'
                    ];
                } else
                {
                    $textList[] = [
                        'text' => $this->fortuneUpText[$fortuneItem['name']]['avoid_text'],
                        'color' => $fortuneItem['color']
                    ];

                }

                $data['fortune_up_btn_show'] = 1; // 有厄运情况 提示提升按钮
            }

            if ($data['fortune_up_btn_show'])
            {
                $data['fortune_up_btn_show'] = $isFortuneUp ? 0 : 1; // 有厄运情况 提示提升按钮
                $data['fortune_up_info'] = [
                    'title' => $isFortuneUp ? '今日运势状况：' : '当前运势状态',
                    'desc' => $isFortuneUp ? '下划线词条对应已提升运势，颜色代表该运势状态。' : '下划线词条对应可提升运势，颜色代表该运势状态。',
                    'text_list' => $textList
                ];
            } else
            {
                $data['fortune_up_info'] = null;
                $data['fortune_up_btn_show'] = 0;
            }
        } else
        {
            $data['fortune_up_btn_show'] = 0;
            $data['fortune_up_info'] = null;
        }

        return $data;
    }

    /**
     * @title 运势日记列表
     * @desc
     * @return \think\response\Json
     * @throws ApiException
     */
    public function note()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $page = input('get.page/d', 1);
        $rid = input('get.rid/d', 0);
        $uid = $this->user['id'];
        $map = ['uid' => $uid, 'isself' => 1];

        $FortuneNoteModel = new FortuneNote();

        $recodeStatus = [];

        if ($rid)
        {
            $recode = (new Recode())->getRecode(['id' => $rid]);
            if (!$recode || $recode['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '档案不存在');
            }
            $map['rid'] = $rid;
            $recodeStatus[$rid] = $recode['status'];
        }

        $map['page'] = $page;
        try
        {
            $data = $FortuneNoteModel->getListPage($map);
        }
        catch (\Exception $e)
        {
            Log::write('获取运势日记信息失败' . $e->getMessage() . var_export(request()->param(), true), 'error', true);
            $data = [
                'total' => 0,
                'per_page' => 10,
                'current_page' => $page,
                'last_page' => 1,
                'data' => []
            ];
        }

        if (isset($data['data']) && !empty($data['data']))
        {
            $array = [];
            foreach ($data['data'] as $k => $v)
            {
                if (!isset($recodeStatus[$v['rid']]))
                {
                    $recode2 = (new Recode())->getRecode(['id' => $v['rid']]);
                    $recodeStatus[$v['rid']] = $recode2['status'];
                }
                $recodeIsDel = $recodeStatus[$v['rid']] ? 0 : 1;
                $array[] = [
                    'id' => (int)$v['id'],
                    'create_time' => date('Y-m-d H:i:s', $v['create_time']),
                    'content' => $v['content'],
                    'state' => (int)$v['state'],
                    'mood' => (int)$v['mood'],
                    'from' => [
                        'rid' => (int)$v['rid'],
                        'time' => date('Y-m-d', $v['time']),
                        'remark' => '每日运势',
                        'icon_url' => config('fortune.thumb'),
                    ],
                    'recode_is_del' => $recodeIsDel,
                    'target' => 'local',
                    'link' => $recodeIsDel ? "fortune_for_day_history?need_auth=2&order_id=&day_note_id={$v['id']}&rid={$v['rid']}" : "day?need_auth=1&rid={$v['rid']}&time=" . date('Y-m-d', $v['time'])
                ];
            }

            $data['data'] = $array;
            return show(200, '列表加载成功', $data);
        }
        return show(200, '还没有运势日记，您可以为每日运势打分哦~', $data);
    }
}
